package javapop.framework.parser;

import javapop.framework.ParseContext;
import javapop.framework.ParseError;
import javapop.framework.ParseInput;
import javapop.framework.ParseResult;
import javapop.framework.Parser;

public class LineComment extends Parser<String> {
	private Parser<?> start;
	private String description;
	
	public LineComment(Parser<?> start) {
		if(start==null) {
			throw new IllegalArgumentException("Start parser must not be <null>");
		}

		this.start = start;
		StringBuffer buf = new StringBuffer();
		buf.append("LineComment[start=");
		buf.append(start.getDescription());
		buf.append("]");
		description = buf.toString();
	}
	
	@Override
	public String getDescription() {
		return description;
	}
	
	@Override
	public boolean isMemoized() {
		return false;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public ParseResult<String> eval(ParseContext<?> ctx, ParseInput input) {
		ParseResult<?> result = start.parse(ctx,input);
		StringBuilder comment = new StringBuilder();
		if(result.isError()) {
			ParseResult error = new ParseError("Expecting "+description);
			return (ParseResult<String>) error;
		}
		while(true) {
			Character ch = input.fetch();
			if(ch==null) {
				return buildResult(comment.toString());
			} else if(ch=='\n') {
				input.next();
				return buildResult(comment.toString());
			}
			input.next();
			comment.append(ch);
		}
		
	}
	
}
